package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static java.awt.SystemColor.menu;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//查询条件
        //完成分页查询，基于mybatis框架提供的分页助手插件完成
        PageHelper.startPage(currentPage,pageSize);

        //select * from t_checkitem limit 0,10
        Page<Role> page = roleDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Role> rows = page.getResult();
        return new PageResult(total,rows);
    }

    @Override
    public void add(Role role,Integer[] roleIds) {
        roleDao.add(role);

        if (roleIds != null && roleIds.length>0){
            this.addRoelAndMenuIds(role.getId(),roleIds);
        }
    }

    @Override
    public Role findByRoleId(Integer roleId) {
        return roleDao.findByRoleId(roleId);
    }

    @Override
    public void delete(Integer roleId) {
        //先删除中间表
        roleDao.deleteCenterByRoleId(roleId);
        roleDao.delete(roleId);
    }

    @Override
    public void edit(Role role,Integer[] roleIds) {
        roleDao.update(role);
        if (roleIds != null && roleIds.length>0){
            Integer roleId = role.getId();
            roleDao.deleteCenterByRoleId(roleId);
            this.addRoelAndMenuIds(roleId,roleIds);
        }
    }

    @Override
    public Set<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Set<Integer> findMenuIdsByRoleId(Integer id) {
        return roleDao.findMenuIdsByRoleId(id);
    }

    /*关联关系*/
    public void addRoelAndMenuIds(Integer roleId,Integer[] menuIds){
        if (menuIds != null && menuIds.length>0) {
            Map map = new HashMap();
            for (Integer menuId : menuIds) {
                map.put("roleId",roleId);
                map.put("menuId",menuId);
                roleDao.addRoelAndMenuIds(map);
            }
        }
    }
}
